// 数据采集控制页面JavaScript

// 状态轮询控制
let statusPollingInterval = null;

document.addEventListener('DOMContentLoaded', function() {
    // 绑定采集按钮事件
    bindScrapeEvents();
    
    // 添加页面加载动画
    document.body.classList.add('fade-in');
});

// 绑定采集相关事件
function bindScrapeEvents() {
    const scrapeClassBtn = document.getElementById('scrapeClassBtn');
    const scrapeTeacherBtn = document.getElementById('scrapeTeacherBtn');
    
    scrapeClassBtn.addEventListener('click', function() {
        startScraping('class');
    });
    
    scrapeTeacherBtn.addEventListener('click', function() {
        startScraping('teacher');
    });
}

// 开始采集
async function startScraping(type) {
    const cookiesInput = document.getElementById('cookiesInput');
    const cookies = cookiesInput.value.trim();
    
    if (!cookies) {
        showError('请先输入有效的Cookies');
        return;
    }
    
    const button = type === 'class' ? document.getElementById('scrapeClassBtn') : document.getElementById('scrapeTeacherBtn');
    const originalText = button.innerHTML;
    
    // 禁用按钮
    button.disabled = true;
    button.innerHTML = '<i class="bi bi-hourglass-split"></i> 采集中...';
    
    try {
        // 构建请求数据
        const requestData = { cookies: cookies };
        
        // 如果是班级采集，添加额外参数
        if (type === 'class') {
            const year = document.getElementById('classYearInput').value.trim();
            const college = document.getElementById('classCollegeInput').value.trim();
            const major = document.getElementById('classMajorInput').value.trim();
            const semester = document.getElementById('classSemesterInput').value.trim();
            
            // 只传递非空参数，空参数表示不限制
            if (year) requestData.year = year;
            if (college) requestData.college_code = college;
            if (major) requestData.major_code = major;
            if (semester) requestData.semester = semester;
        }
        
        // 如果是教师采集，添加教师筛选参数
        if (type === 'teacher') {
            const teacherName = document.getElementById('teacherNameInput').value.trim();
            const teacherId = document.getElementById('teacherIdInput').value.trim();
            const semester = document.getElementById('teacherSemesterInput').value.trim();
            
            if (teacherName) requestData.teacher_name = teacherName;
            if (teacherId) requestData.teacher_id = teacherId;
            if (semester) requestData.semester = semester;
        }
        
        const response = await fetch(`/api/scrape/${type}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(requestData)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            showSuccess(result.message);
            document.getElementById('scrapingStatus').style.display = 'block';
            // 启动状态轮询
            startStatusPolling();
        } else {
            showError(result.error || '采集启动失败');
        }
    } catch (error) {
        showError('网络错误: ' + error.message);
    } finally {
        // 恢复按钮
        button.disabled = false;
        button.innerHTML = originalText;
    }
}

// 启动状态轮询
function startStatusPolling() {
    if (statusPollingInterval) {
        clearInterval(statusPollingInterval);
    }
    statusPollingInterval = setInterval(updateScrapingStatus, 3000); // 每3秒更新一次状态
}

// 停止状态轮询
function stopStatusPolling() {
    if (statusPollingInterval) {
        clearInterval(statusPollingInterval);
        statusPollingInterval = null;
    }
}

// 更新采集状态
async function updateScrapingStatus() {
    try {
        const response = await fetch('/api/scrape/status');
        const status = await response.json();
        
        // 更新班级采集状态
        const classMessage = document.getElementById('classMessage');
        const classProgress = document.getElementById('classProgress');
        const classStatus = document.getElementById('classStatus');
        
        classMessage.textContent = status.class_message || '-';
        classProgress.style.width = status.class_progress + '%';
        
        if (status.class_scraping) {
            classStatus.textContent = '采集中';
            classStatus.className = 'badge bg-primary';
        } else {
            classStatus.textContent = '待机中';
            classStatus.className = 'badge bg-light text-dark';
        }
        
        // 更新教师采集状态
        const teacherMessage = document.getElementById('teacherMessage');
        const teacherProgress = document.getElementById('teacherProgress');
        const teacherStatus = document.getElementById('teacherStatus');
        
        teacherMessage.textContent = status.teacher_message || '-';
        teacherProgress.style.width = status.teacher_progress + '%';
        
        if (status.teacher_scraping) {
            teacherStatus.textContent = '采集中';
            teacherStatus.className = 'badge bg-info';
        } else {
            teacherStatus.textContent = '待机中';
            teacherStatus.className = 'badge bg-light text-dark';
        }
        
        // 如果采集完成，显示成功消息并停止轮询
        if (status.class_message && status.class_message.includes('采集完成')) {
            setTimeout(() => {
                showSuccess('班级课表采集完成！');
                // 如果两个采集都完成了，停止轮询
                if (!status.class_scraping && !status.teacher_scraping) {
                    stopStatusPolling();
                }
            }, 2000);
        }
        
        if (status.teacher_message && status.teacher_message.includes('采集完成')) {
            setTimeout(() => {
                showSuccess('教师课表采集完成！');
                // 如果两个采集都完成了，停止轮询
                if (!status.class_scraping && !status.teacher_scraping) {
                    stopStatusPolling();
                }
            }, 2000);
        }
        
        // 如果没有采集在进行，停止轮询
        if (!status.class_scraping && !status.teacher_scraping) {
            stopStatusPolling();
        }
        
    } catch (error) {
        console.error('更新采集状态失败:', error);
    }
}

// 显示成功消息
function showSuccess(message) {
    showMessage(message, 'success');
}

// 显示错误消息
function showError(message) {
    showMessage(message, 'danger');
}

// 显示消息
function showMessage(message, type) {
    const messageArea = document.getElementById('messageArea');
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show mt-3`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    messageArea.appendChild(alertDiv);
    
    // 5秒后自动移除消息
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
